package com.gukun.springboot.tdengine.service.backuprecover.config;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 对于不同类型的任务线程池有不同配置
 * CPU密集型任务 CPU核心数 N  核心线程可以设置为N，接近CPU核心数
 * IO密集型任务 CPU核心数 N 2N
 * @author zhang
 */
public class ThreadPool {

    public static final int CORE_POOL_SIZE = Runtime.getRuntime().availableProcessors();
    public static final int MAX_POOL_SIZE = Runtime.getRuntime().availableProcessors();
    public static final int QUEUE_CAPACITY = 100;
    public static final Long KEEP_ALIVE_TIME = 30L;

    public static ThreadPoolExecutor threadPoolExecutor() {
        return new ThreadPoolExecutor(
                CORE_POOL_SIZE,
                MAX_POOL_SIZE,
                KEEP_ALIVE_TIME,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(QUEUE_CAPACITY),
                new ThreadPoolExecutor.AbortPolicy()
        );
    }

    public static ThreadPoolExecutor threadPoolExecutor(int maxPoolSize,int corePoolSize) {
        if(maxPoolSize > MAX_POOL_SIZE){
            maxPoolSize = MAX_POOL_SIZE;
        }
        if(corePoolSize > CORE_POOL_SIZE){
            corePoolSize = CORE_POOL_SIZE;
        }
        return new ThreadPoolExecutor(
                corePoolSize,
                maxPoolSize,
                KEEP_ALIVE_TIME,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(QUEUE_CAPACITY),
                new ThreadPoolExecutor.AbortPolicy()
        );
    }

    public static ThreadPoolExecutor threadPoolExecutor(int maxPoolSize,int corePoolSize, int queueCapacity) {
        return new ThreadPoolExecutor(
                corePoolSize,
                maxPoolSize,
                KEEP_ALIVE_TIME,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(queueCapacity),
                new ThreadPoolExecutor.AbortPolicy()
        );
    }
}
